// 学生管理系统 - 主JavaScript文件

// 全局应用对象
window.StudentManagementApp = {
  // 配置
  config: {
    toastDuration: 5000,
    animationDuration: 300
  },
  
  // 初始化
  init() {
    this.initSidebar();
    this.initToast();
    this.initModal();
    this.initDropdowns();
    this.initForms();
    this.initTheme();
    console.log('学生管理系统已初始化');
  },
  
  // 侧边栏功能
  initSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const toggleBtn = document.querySelector('[data-sidebar-toggle]');
    const navLinks = document.querySelectorAll('.nav-link[data-toggle="collapse"]');
    
    // 切换侧边栏
    if (toggleBtn) {
      toggleBtn.addEventListener('click', () => {
        sidebar.classList.toggle('collapsed');
        localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));
      });
    }
    
    // 恢复侧边栏状态
    const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    if (isCollapsed && sidebar) {
      sidebar.classList.add('collapsed');
    }
    
    // 处理子菜单展开/收起
    navLinks.forEach(link => {
      link.addEventListener('click', (e) => {
        e.preventDefault();
        const targetId = link.getAttribute('data-target');
        const target = document.querySelector(targetId);
        const isExpanded = link.getAttribute('aria-expanded') === 'true';
        
        // 更新aria-expanded属性
        link.setAttribute('aria-expanded', !isExpanded);
        
        // 切换子菜单显示
        if (target) {
          if (isExpanded) {
            target.style.maxHeight = '0';
            target.style.opacity = '0';
          } else {
            target.style.maxHeight = target.scrollHeight + 'px';
            target.style.opacity = '1';
          }
        }
      });
    });
    
    // 设置当前页面的活动状态
    this.setActiveNavItem();
    
    // 移动端侧边栏处理
    this.initMobileSidebar();
  },
  
  // 移动端侧边栏
  initMobileSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.createElement('div');
    overlay.className = 'sidebar-overlay';
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
    `;
    
    document.body.appendChild(overlay);
    
    // 移动端切换按钮
    const mobileToggle = document.createElement('button');
    mobileToggle.innerHTML = '<i class="fas fa-bars"></i>';
    mobileToggle.className = 'mobile-sidebar-toggle';
    mobileToggle.style.cssText = `
      position: fixed;
      top: 1rem;
      left: 1rem;
      z-index: 1001;
      background: rgba(59, 130, 246, 0.9);
      border: none;
      color: white;
      padding: 0.75rem;
      border-radius: 0.5rem;
      cursor: pointer;
      display: none;
      box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
    `;
    
    document.body.appendChild(mobileToggle);
    
    // 响应式显示/隐藏
    const checkMobile = () => {
      if (window.innerWidth <= 1024) {
        mobileToggle.style.display = 'block';
      } else {
        mobileToggle.style.display = 'none';
        sidebar.classList.remove('show');
        overlay.style.opacity = '0';
        overlay.style.visibility = 'hidden';
      }
    };
    
    window.addEventListener('resize', checkMobile);
    checkMobile();
    
    // 移动端切换事件
    mobileToggle.addEventListener('click', () => {
      sidebar.classList.toggle('show');
      if (sidebar.classList.contains('show')) {
        overlay.style.opacity = '1';
        overlay.style.visibility = 'visible';
      } else {
        overlay.style.opacity = '0';
        overlay.style.visibility = 'hidden';
      }
    });
    
    // 点击遮罩关闭
    overlay.addEventListener('click', () => {
      sidebar.classList.remove('show');
      overlay.style.opacity = '0';
      overlay.style.visibility = 'hidden';
    });
  },
  
  // 设置活动导航项
  setActiveNavItem() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('.nav-link');
    
    navLinks.forEach(link => {
      const href = link.getAttribute('href');
      if (href && currentPath.includes(href)) {
        link.classList.add('active');
        
        // 展开父级菜单
        const parentSubmenu = link.closest('.nav-submenu');
        if (parentSubmenu) {
          const parentToggle = document.querySelector(`[data-target="#${parentSubmenu.id}"]`);
          if (parentToggle) {
            parentToggle.setAttribute('aria-expanded', 'true');
            parentSubmenu.style.maxHeight = parentSubmenu.scrollHeight + 'px';
            parentSubmenu.style.opacity = '1';
          }
        }
      }
    });
  },
  
  // Toast通知系统
  initToast() {
    // 创建Toast容器
    if (!document.querySelector('.toast-container')) {
      const container = document.createElement('div');
      container.className = 'toast-container';
      document.body.appendChild(container);
    }
  },
  
  // 显示Toast通知
  showToast(type, title, message, duration = null) {
    const container = document.querySelector('.toast-container');
    const toast = document.createElement('div');
    const toastId = 'toast-' + Date.now();
    
    duration = duration || this.config.toastDuration;
    
    // 设置图标
    const icons = {
      success: 'fas fa-check-circle',
      warning: 'fas fa-exclamation-triangle',
      error: 'fas fa-times-circle',
      info: 'fas fa-info-circle'
    };
    
    toast.className = `toast ${type}`;
    toast.id = toastId;
    toast.innerHTML = `
      <i class="toast-icon ${icons[type]}"></i>
      <div class="toast-content">
        <div class="toast-title">${title}</div>
        <div class="toast-message">${message}</div>
      </div>
      <button class="toast-close" onclick="StudentManagementApp.closeToast('${toastId}')">
        <i class="fas fa-times"></i>
      </button>
    `;
    
    container.appendChild(toast);
    
    // 自动关闭
    setTimeout(() => {
      this.closeToast(toastId);
    }, duration);
    
    return toastId;
  },
  
  // 关闭Toast
  closeToast(toastId) {
    const toast = document.getElementById(toastId);
    if (toast) {
      toast.style.animation = 'slideOutRight 0.3s ease-out';
      setTimeout(() => {
        if (toast.parentNode) {
          toast.remove();
        }
      }, 300);
    }
  },
  
  // 模态框系统
  initModal() {
    // 处理模态框关闭
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('modal-overlay')) {
        this.closeModal();
      }
      
      if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) {
        this.closeModal();
      }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        this.closeModal();
      }
    });
  },
  
  // 显示模态框
  showModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.classList.add('show');
      document.body.style.overflow = 'hidden';
    }
  },
  
  // 关闭模态框
  closeModal() {
    const modals = document.querySelectorAll('.modal-overlay.show');
    modals.forEach(modal => {
      modal.classList.remove('show');
    });
    document.body.style.overflow = '';
  },
  
  // 下拉菜单
  initDropdowns() {
    document.addEventListener('click', (e) => {
      const dropdown = e.target.closest('[data-dropdown]');
      
      if (dropdown) {
        e.preventDefault();
        const menu = dropdown.querySelector('.dropdown-menu');
        const isOpen = menu.classList.contains('show');
        
        // 关闭所有下拉菜单
        document.querySelectorAll('.dropdown-menu.show').forEach(m => {
          m.classList.remove('show');
        });
        
        // 切换当前下拉菜单
        if (!isOpen) {
          menu.classList.add('show');
        }
      } else {
        // 点击外部关闭所有下拉菜单
        document.querySelectorAll('.dropdown-menu.show').forEach(m => {
          m.classList.remove('show');
        });
      }
    });
  },
  
  // 表单处理
  initForms() {
    // 表单验证
    document.addEventListener('submit', (e) => {
      const form = e.target;
      if (form.classList.contains('needs-validation')) {
        e.preventDefault();
        this.validateForm(form);
      }
    });
    
    // 实时验证
    document.addEventListener('blur', (e) => {
      if (e.target.classList.contains('form-control')) {
        this.validateField(e.target);
      }
    }, true);
  },
  
  // 验证表单
  validateForm(form) {
    const fields = form.querySelectorAll('.form-control[required]');
    let isValid = true;
    
    fields.forEach(field => {
      if (!this.validateField(field)) {
        isValid = false;
      }
    });
    
    if (isValid) {
      this.showToast('success', '成功', '表单验证通过');
      // 这里可以提交表单
    } else {
      this.showToast('error', '错误', '请检查表单中的错误');
    }
    
    return isValid;
  },
  
  // 验证字段
  validateField(field) {
    const value = field.value.trim();
    const type = field.type;
    let isValid = true;
    let errorMessage = '';
    
    // 必填验证
    if (field.hasAttribute('required') && !value) {
      isValid = false;
      errorMessage = '此字段为必填项';
    }
    
    // 邮箱验证
    if (type === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      isValid = false;
      errorMessage = '请输入有效的邮箱地址';
    }
    
    // 电话验证
    if (field.classList.contains('phone') && value && !/^1[3-9]\d{9}$/.test(value)) {
      isValid = false;
      errorMessage = '请输入有效的手机号码';
    }
    
    // 更新UI
    this.updateFieldValidation(field, isValid, errorMessage);
    
    return isValid;
  },
  
  // 更新字段验证状态
  updateFieldValidation(field, isValid, errorMessage) {
    const formGroup = field.closest('.form-group');
    let errorElement = formGroup.querySelector('.form-error');
    
    if (isValid) {
      field.classList.remove('error');
      if (errorElement) {
        errorElement.remove();
      }
    } else {
      field.classList.add('error');
      if (!errorElement) {
        errorElement = document.createElement('div');
        errorElement.className = 'form-error';
        formGroup.appendChild(errorElement);
      }
      errorElement.textContent = errorMessage;
    }
  },
  
  // 主题系统
  initTheme() {
    // 检测系统主题偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const savedTheme = localStorage.getItem('theme');
    
    // 设置默认主题（暗黑）
    if (!savedTheme) {
      document.documentElement.setAttribute('data-theme', 'dark');
      localStorage.setItem('theme', 'dark');
    } else {
      document.documentElement.setAttribute('data-theme', savedTheme);
    }
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      if (!localStorage.getItem('theme')) {
        document.documentElement.setAttribute('data-theme', e.matches ? 'dark' : 'light');
      }
    });
  },
  
  // 切换主题
  toggleTheme() {
    const currentTheme = document.documentElement.getAttribute('data-theme');
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    
    document.documentElement.setAttribute('data-theme', newTheme);
    localStorage.setItem('theme', newTheme);
    
    this.showToast('info', '主题切换', `已切换到${newTheme === 'dark' ? '暗黑' : '明亮'}主题`);
  },
  
  // 工具函数
  utils: {
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      
      return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day);
    },
    
    // 防抖函数
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },
    
    // 节流函数
    throttle(func, limit) {
      let inThrottle;
      return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
          func.apply(context, args);
          inThrottle = true;
          setTimeout(() => inThrottle = false, limit);
        }
      };
    },
    
    // 生成随机ID
    generateId() {
      return 'id-' + Math.random().toString(36).substr(2, 9);
    },
    
    // 深拷贝
    deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    }
  }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  StudentManagementApp.init();
});

// 导出到全局
window.App = StudentManagementApp;
